package cn.cdutetc.library.controller;

import cn.cdutetc.library.common.ApiResponse;
import cn.cdutetc.library.common.BackupUtils;
import cn.cdutetc.library.entity.pojo.BackupRecord;
import cn.cdutetc.library.mapper.BackupRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 备份调试控制器
 */
@RestController
@RequestMapping("/api/backup/debug")
@CrossOrigin(originPatterns = "*")
public class BackupDebugController {

    @Autowired
    private BackupRecordMapper backupRecordMapper;

    @Autowired
    private BackupUtils backupUtils;

    /**
     * 检查备份文件内容
     */
    @GetMapping("/check-backup/{backupId}")
    public ApiResponse<Map<String, Object>> checkBackupFile(@PathVariable Integer backupId) {
        try {
            BackupRecord backup = backupRecordMapper.selectById(backupId);
            if (backup == null) {
                return ApiResponse.error("备份记录不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("backupId", backup.getBackupId());
            result.put("backupName", backup.getBackupName());
            result.put("backupPath", backup.getBackupPath());
            result.put("backupSize", backup.getBackupSize());
            result.put("backupStatus", backup.getBackupStatus());

            // 检查文件是否存在
            boolean fileExists = Files.exists(Paths.get(backup.getBackupPath()));
            result.put("fileExists", fileExists);

            if (fileExists) {
                // 读取文件内容的前几行
                StringBuilder content = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(new FileReader(backup.getBackupPath()))) {
                    String line;
                    int lineCount = 0;
                    while ((line = reader.readLine()) != null && lineCount < 20) {
                        content.append(line).append("\n");
                        lineCount++;
                    }
                }
                result.put("fileContent", content.toString());
                result.put("fileSize", Files.size(Paths.get(backup.getBackupPath())));
            }

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("检查备份文件失败: " + e.getMessage());
        }
    }


    /**
     * 获取所有备份记录
     */
    @GetMapping("/list")
    public ApiResponse<Object> getAllBackups() {
        try {
            return ApiResponse.success(backupRecordMapper.selectList(null));
        } catch (Exception e) {
            return ApiResponse.error("获取备份列表失败: " + e.getMessage());
        }
    }
}
